package com.reshare.interceptors;

import com.reshare.bean.User;
import com.reshare.exceptions.NoLoginException;
import com.reshare.service.UserService;
import com.reshare.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class NoLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.contains("index") || uri.contains("toRegister")) {
            return true;
        }

        Integer userId = LoginUserUtil.releaseUserIdFromCookie(request);
        User user = userService.selectByPrimaryKey(userId);
        if (userId == null || user == null) {

            request.getRequestDispatcher("/index").forward(request, response);

            return false;
        }
        return true;
    }

}
